package com.dlwx.parttimetalent.service;

import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.ui.MainActivity;
import com.dlwx.parttimetalent.ui.OrderEmployeActivity;
import com.dlwx.parttimetalent.ui.PublishDetailActivity;
import com.dlwx.parttimetalent.utils.ActivityUtils;
import com.dlwx.parttimetalent.utils.BackgroundUtil;
import com.dlwx.parttimetalent.utils.JudgePhoneBrand;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.SoundPlayer;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "wch";
//    private NotiFicaBean notiFicaBean;
	private Context ctx;
	private PendingIntent pi;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.ctx = context;
		try {
			Bundle bundle = intent.getExtras();
//			Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

			if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
				String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
				Log.i(TAG, "[MyReceiver] 接收Registration Id : " + regId);
				//send the Registration Id to your server...

			} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
				Log.i(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
				processCustomMessage(context, bundle,false);

			} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
				Log.i(TAG, "[MyReceiver] 接收到推送下来的通知");
				SoundPlayer.playDingDong(context);
				int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
				Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
                processCustomMessage(context, bundle,false);

			} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
				Log.i("wch", "[MyReceiver] 用户点击打开了通知");
//				Intent inten = null;
//				inten = new Intent(context, MainActivity.class);
//                        inten.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//                        context.startActivity(inten);
				processCustomMessage(context, bundle,true);
			} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
				Log.i(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
				//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

			} else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
				boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
				Log.i(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
			} else {
				Log.i(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
			}
		} catch (Exception e){
            Log.i("wch",e.getMessage());
		}

	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
				if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
					Log.i(TAG, "This message has no Extra data");
					continue;
				}

				try {
					JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
					Iterator<String> it =  json.keys();

					while (it.hasNext()) {
						String myKey = it.next().toString();
						sb.append("\nkey:" + key + ", value: [" +
								myKey + " - " +json.optString(myKey) + "]");
					}
				} catch (JSONException e) {
					Log.e(TAG, "Get message extra JSON error!");
				}

			} else {
                String string = bundle.getString(key);
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}
	
	//send msg to MainActivity
	private void processCustomMessage(Context context, Bundle bundle,boolean isClick) {
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//		showNot(message);
		String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
        msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
		try {
			JSONObject extrasJson = new JSONObject(extras);
			String id = extrasJson.optString("id");
			String money = extrasJson.optString("money");
			int  type = extrasJson.optInt("pos");
			if(!isClick){
				if(type==4){
					SoundPlayer.playSoundByMedia(context);
				}
			}
			jumpTo(context,id,type,isClick);
		} catch (Exception e) {
			LogUtils.w("Unexpected: extras is not a valid json", e);
		}
//		发送广播,更新首页消息数字（订单消息，系统消息）
		Intent i=new Intent();
		i.setAction(Constant.ACTION_HX);
		context.sendBroadcast(i);
	}

	private void showNot(String mess){
		Intent inten = null;
		inten = new Intent(ctx, MainActivity.class);
		inten.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
		pi = PendingIntent.getActivity(ctx, 0, inten, 0);
		//获取NotificationManager实例
		NotificationManager notifyManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
		//实例化NotificationCompat.Builde并设置相关属性
		NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx,"")
				//设置小图标
				.setSmallIcon(R.mipmap.logopro)
				//设置通知标题
				.setContentTitle("约神")
				.setContentIntent(pi)
				//设置通知内容
				.setContentText(mess);
		builder.setDefaults(Notification.DEFAULT_ALL);
		//设置通知时间，默认为系统发出通知的时间，通常不用设置
		//.setWhen(System.currentTimeMillis());
		//通过builder.build()方法生成Notification对象,并发送通知,id=1
		notifyManager.notify(1, builder.build());

	}

	private void jumpTo(Context context,String id,int pos,boolean isClick){
		//获取接收到推送时的系统时间
		Calendar rightNow = Calendar.getInstance();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = fmt.format(rightNow.getTime());
		Intent i = null;
//
		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		boolean isScreenOn = false;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
			isScreenOn = pm.isInteractive();
		}else{
			isScreenOn = pm.isScreenOn();
		}

		KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
//        Log.d("CCC","km:"+ km.inKeyguardRestrictedInputMode());
//       判断锁屏界面是否在显示
//        boolean b= (boolean) SPUtils.get(context,"showScreenMsg",false);

		Boolean isForeground= BackgroundUtil.getRunningAppProcesses(context, context.getPackageName());
		if (JudgePhoneBrand.SYS_MIUI.equals(JudgePhoneBrand.getSystem())) {
			if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.LOLLIPOP){
				isForeground= BackgroundUtil.getRunningTask(context, context.getPackageName());
			}
		}
		boolean isLockShow= ActivityUtils.isTopActivity("com.renhuikeji.wanlb.wanlibao","com.renhuikeji.wanlb.wanlibao.activity.LockScreenMsgActivity",context);
//       当屏幕被点亮,任务在前台,并且锁屏没在top
		if(!isScreenOn){

			lightScreen(context);
		}
		//		pos=> 1 系统消息 2订单消息 3 交易消息 4 未接受 5 红包  id=>"红包id"
		switch (pos){
			case 1:
				i = new Intent(context, MainActivity.class);
				i.putExtra("type",2);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				if(isClick){
					context.startActivity(i);
				}
				break;
			case 2:
				i = new Intent(context, MainActivity.class);
				i.putExtra("type",2);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				if(isClick){
					context.startActivity(i);
				}
				break;
			case 3:
				i = new Intent(context, MainActivity.class);
				i.putExtra("type",2);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				if(isClick){
					context.startActivity(i);
				}
				break;
			case 4:
				if(isClick){
					i = new Intent(context, MainActivity.class);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
					context.startActivity(i);
				}else{

					i = new Intent(context, OrderEmployeActivity.class);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					i.putExtra("flag",1);
					context.startActivity(i);
				}
				break;
			case 5:
				// 发送广播
				i=new Intent();
				i.setAction(Constant.RECEIVER_ACCOUNT);
				i.putExtra("type",Constant.MSG_RED_PACEKT);
				i.putExtra("id",id);
				context.sendBroadcast(i);
				break;
			case 6:
				i=new Intent(context, PublishDetailActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.putExtra( Constant.IS_ME,false);
				i.putExtra("id",id);
				if(isClick){
					context.startActivity(i);
				}
				break;
		}

	}

	/**
	 * 点亮屏幕
	 */
	private void lightScreen(Context context) {
		PowerManager pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
		PowerManager.WakeLock wakeLock;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
			if (!pm.isInteractive()) {
				wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
						| PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
				wakeLock.acquire();
			}
		} else {
			if (!pm.isScreenOn()) {
				wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
						PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
				wakeLock.acquire();
			}
		}
      /*  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(wakeLock.isHeld()){
                    wakeLock.release();
                }
            }
        },3000);*/
	}
}
